<?php

class HotSquareModel
{
    private $hotSquareKeyPrefix =   'HS/';
    private $slaveKey           =   '/slave';
    private $diaryListCacheModel;
    
    public function __construct(){
        $this->diaryListCacheModel    =  new DiaryListCacheModel();
    }
    
    public function setSquareInfo($info)/*{{{*/
    {
        if (empty($info['eUid']) || strlen($info['eNickname']) < 1)
        {
            AC::$errorNo    =   'HSM001';
            return  FALSE;
        }

        if (empty($info['type']) || empty($info['bodyId']))
        {
            AC::$errorNo    =   'HSM002';
            return  FALSE;
        }
        $data['eUid']       =   $info['eUid'];
        $data['eNickname']  =   $info['eNickname'];
        $data['bodyId']     =   $info['bodyId'];
        $data['type']       =   $info['type'];
        $data['time']       =   AC::SERVER_TIME;

        isset($info['content']) &&  $data['content']    =   $info['content'];

        $key    =   $this->hotSquareKeyPrefix. 0;
        $result =   Storage::addData($key, $data);
        
        if ($info['type'] != AC::FEED_REPOST){
            $this->diaryListCacheModel->addSquareTimeline($data['bodyId'], $info['label']);
        }
        if (empty($result)) AC::$errorNo    =   'HSM003';
        return  $result;
    }/*}}}*/

    public function getSquareList($info)/*{{{*/
    {
        $start  =   0;
        $length =   AC::FEED_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        if (empty($info['id']))
        {
            $where  =   NULL;
        }
        else
        {
            $where  =   ' id > '. $info['id'];
        }
        $orderBy=   ' id DESC ';
        $key    =   $this->hotSquareKeyPrefix. 0;
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/
   
    public function getDiaryInfoUseLike($info)/*{{{*/
    {
        return array();
        $start  =   0;
        $length =   AC::FEED_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if (!empty($info['id']))        $like[] =   ' `id` > '. $info['id'];
        if (!empty($info['uid']))       $like[] =   ' `eUid` like "'. $info['uid']. '"';
        if (!empty($info['nickname']))  $like[] =   ' `eNickname` like "'. $info['nickname']. '"';
        if (!empty($info['title']))     $like[] =   ' `content` like "'. $info['title']. '"';
        if (empty($like))   $where  =   NULL;
        else    $where  =   implode(' AND ', $like);
        if ($start  <   0)  $start  =   0;

        $orderBy=   ' id DESC ';
        $key    =   $this->hotSquareKeyPrefix. '0'.$this->slaveKey;
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);

        return  $result;
    }/*}}}*/
    // 搜索日记
    public function getSearchDiaryInfo($info)/*{{{*/
    {
        $start  =   0;
        $length =   AC::FEED_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if (intval($start)  <   0)  $start  =   0;
        
        $ids = array();
        if (!empty($info['title']) || !empty($info['content'])){
            $keyword = '';
            !empty($info['title'])   && $keyword = $info['title'] ;
            !empty($info['content']) && $keyword = $info['content'];
            
            $list = $this->sphinxSearch($keyword, $start, $length);
            if (!empty($list['matches'])){
                foreach ($list['matches'] as $val){
                    $tmp = array();
                    $tmp['bodyId'] = $val['attrs']['bodyid'];
                    $tmp['id']     = $val['id'];
                    $ids[]         = $tmp;
                }
            }
        }
        
        return  $ids;
    }/*}}}*/
    
    // 搜索
    private function sphinxSearch($keyword, $start, $length){
        $client = RedisPool::initSphinx();
        if (empty($client)) return array();
        // 设置返回数据的排序
        $client->setSortMode(SPH_SORT_ATTR_DESC, 'time');
        // 分页
    
        $client->SetLimits($start, $length, '1000');
        // 搜索,1=日记,2=用户
        $searchd = array(
                '1' => 'hot_main,hot_delta',
                '2' => 'user_main,user_delta',
        );
        return $client->query($keyword, $searchd[1]);
    }
    
    // 搜索用户
    public function getSearchUsersByTag($uid, $info)/*{{{*/
    {
        $start  =   0;
        $length =   AC::FEED_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if (intval($start)  <   0)  $start  =   0;
    
        $uids = array();
        if (!empty($info['tags_str'])){
            $keyword = '';
            !empty($info['tags_str']) && $keyword = $info['tags_str'];
            
            $list = $this->sphinxSearchUsersByTag($keyword, $start, $length);
            if (!empty($list['matches'])){
                foreach ($list['matches'] as $val){
                    $uids[] = $val['id'];
                }
            }
        }

        $uids = $this->filterSelfAndOfficials($uid, $uids);
        return  $uids;
    }/*}}}*/
    

    public function filterSelfAndOfficials ($uid, $uids) {
        if (empty($uid)) return $uids;
         
        // 过滤已关注
        $friends = 	 $this->diaryListCacheModel->getFriendsList($uid);
         
        $filters = AC::$officialAccounts['recommend'];
        if (!in_array($uid, $filters)) {
            $filters[] = $uid;
        }
        $friends =  array_merge($friends, $filters);
        $uids    =   array_diff($uids, $friends);
        return $uids;
    }
    
    
    // 标签搜索用户
    private function sphinxSearchUsersByTag($keyword, $start, $length){
        $client = RedisPool::initSphinx();
        if (empty($client)) return array();
        
        $client->SetMatchMode(SPH_MATCH_ANY);
        $client->SetLimits($start, $length, '1000');
        // 搜索,1=日记,2=用户
        $searchd = array(
                '1' => 'tag_main',
        );
        return $client->query($keyword, $searchd[1]);
    }
    
    // 老版本搜索
    public function oldSearchDiaryInfo($info){
        return array();
        $start  =   0;
        $length =   AC::FEED_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if (!empty($info['id']))        $like[] =   ' `id` < '. $info['id'];
        if (!empty($info['uid']))       $like[] =   ' `eUid` like "'. $info['uid']. '"';
        if (!empty($info['nickname']))  $like[] =   ' `eNickname` like "'. $info['nickname']. '"';
        if (!empty($info['title']))     $like[] =   ' `content` like "'. $info['title']. '"';
        if (empty($like))   $where  =   NULL;
        else    $where  =   implode(' AND ', $like);
        if ($start  <   0)  $start  =   0;
        
        $orderBy=   ' id DESC ';
        $key    =   $this->hotSquareKeyPrefix. '0'.$this->slaveKey;
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        
        return  $result;
    }
    
    public function getSquareListUp($info)/*{{{*/
    {
        if (empty($info['id']))
        {
            return  $this->getSquareList($info);
        }

        $start  =   0;
        $length =   AC::FEED_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $orderBy=   ' id ASC ';
        $where  =   ' id > '. $info['id'];
        $key    =   $this->hotSquareKeyPrefix. 0;
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/

    public function getSquareListDown($info)/*{{{*/
    {
        if (empty($info['id']))
        {
            return  $this->getSquareList($info);
        }

        $start  =   0;
        $length =   AC::FEED_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $orderBy=   ' id DESC ';
        $where  =   ' id < '. $info['id'];
        $key    =   $this->hotSquareKeyPrefix. 0;
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/

    public function getSquareLatestUserList($info)/*{{{*/
    {
        $start  =   0;
        $length =   AC::FEED_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $orderBy=   ' id DESC ';
        $fields =   ' eUid, eNickname ';
        $key    =   $this->hotSquareKeyPrefix. 0;
        $result =   Storage::getFieldsManyData($key, $fields, $orderBy, $start, $length * 2);
        if (empty($result)  ||  !is_array($result)) return  $result;

        $i          =   0;
        $userList   =   array();
        $userList[1]   = array('uid' => '1','nickname'=>'粉粉日记');   
        foreach ($result    as  $user)
        {
            if (AC::HOST_UID    ==  $user['eUid'])  continue;
            $userList[$user['eUid']]    =   array('uid' => $user['eUid'], 'nickname' => $user['eNickname']);
            $userNum    =   count($userList);
            if (++$i <  $length)        continue;
            if ($length ==  $userNum)   break;
        }

        return  array_values($userList);
    }/*}}}*/

    public function getDailyDiaryNum()/*{{{*/
    {
        $key    =   $this->chatModelKeyPrefix. 0;
        $dbSql  =   ' SELECT count(*) as num, FROM_UNIXTIME(`time`, "%Y%m%d") as ymd FROM hotSquare_0 GROUP BY ymd ';
        $result =   Storage::fetchDbSentence($key, $dbSql, 2);

        return  $result;
    }/*}}}*/

    public function getDailyUidNum()/*{{{*/
    {
        $key    =   $this->chatModelKeyPrefix. 0;
        $dbSql  =   ' SELECT count(*) as num, FROM_UNIXTIME(`time`, "%Y%m%d") as ymd FROM (SELECT eUid as uid, time FROM hotSquare_0 GROUP BY uid) as tmp GROUP BY ymd ';
        $result =   Storage::fetchDbSentence($key, $dbSql, 2);

        return  $result;
    }/*}}}*/

    public function removeSquare($info)/*{{{*/
    {
        if (empty($info['id'])  ||  empty($info['uid']))
        {
            AC::$errorNo    =   'HSM004';
            return  FALSE;
        }

        $key    =   $this->hotSquareKeyPrefix. 0;
        $where  =   array('id'  =>  $info['id'], 'eUid' => $info['uid']);
        $result =   Storage::delConditionData($key, $where);

        return  $result;
    }/*}}}*/

}


